package com.hhhn.wk.main.tab2.view.xiangqing.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hhhn.wk.R;
import com.hhhn.wk.base.BaseActivity;
import com.hhhn.wk.base.BaseFragment;
import com.hhhn.wk.config.Config;
import com.hhhn.wk.main.tab2.entity.Commodity;
import com.hhhn.wk.main.tab2.view.xiangqing.activity.CommodityXQActivity;
import com.hhhn.wk.main.tab2.view.xiangqing.adapter.ClassifyGridViewAdapter;
import com.hhhn.wk.main.tab2.view.xiangqing.adapter.Q2_List_Adapter;
import com.hhhn.wk.main.tab2.view.xiangqing.bean.Evaluate;
import com.hhhn.wk.utils.AllPublic;
import com.hhhn.wk.utils.ToastUtils;
import com.hhhn.wk.widget.adapter.MyAdaper;
import com.hhhn.wk.widget.adapter.ViewHolder;
import com.hhhn.wk.widget.customview.MyGridView;
import com.hhhn.wk.widget.customview.MyListView;
import com.hhhn.wk.widget.wkpulltorefreshlayout.BaseRefreshListener;
import com.hhhn.wk.widget.wkpulltorefreshlayout.PullToRefreshLayout;
import com.hhhn.wk.widget.wkpulltorefreshlayout.ViewStatus;

import org.json.JSONArray;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;

/**
 * item页ViewPager里的评价Fragment
 */
public class GoodsCommentFragment extends BaseFragment{
    /*listView*/
    private ListView mLoadListView;
    private PullToRefreshLayout mPullToRefreshLayout;
    public static ArrayList<Evaluate> mArrayList=new ArrayList<Evaluate>();
    private static Q2_List_Adapter mAdapter;
    private int page=1;
    private int refresh = 0;//0 第一次进入  1下拉刷新  2上啦加载
    private boolean isWU = false;
    private int type=0;
    private Context context;
    private BaseActivity activity;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    if (mArrayList.size() == 0) {
                        handler.sendEmptyMessage(2);
                    } else {
                        loadData();
                    }
                    break;
                case 2:
                    mPullToRefreshLayout.showView(ViewStatus.EMPTY_STATUS);////空数据
                   mActivity. dismissLoad();
                    break;
                case 3:
                    mPullToRefreshLayout.showView(ViewStatus.ERROR_STATUS);////网络错误
                    mActivity.  dismissLoad();
                    break;
            }
            super.handleMessage(msg);
        }
    };
    private View rootView;
    String goods_id="";
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_goods_comment, null);
        savedInstanceState=getArguments();
        goods_id = savedInstanceState.getString("goods_id");
        Log.d("商品评价链接id", "onCreateView: "+goods_id);
         mLoadListView=  rootView .findViewById(R.id.mLoadListView);
        mPullToRefreshLayout =   rootView . findViewById(R.id.activity_list);
        context=mActivity;
        activity=mActivity;

        initClickinitClick();
        getJSON();
        return rootView;
    }

    private void initClickinitClick() {
        mPullToRefreshLayout.setRefreshListener(new BaseRefreshListener() {
            @Override
            public void refresh() {
                upView();
            }
            @Override
            public void loadMore() {
                if (isWU) {
                    ToastUtils.showShortToast(context,"暂无更多");
                    mPullToRefreshLayout.showView(ViewStatus.CONTENT_END);//暂无更多
                } else {
                    refresh = 2;
                    page++;
                    if (mAdapter!=null){
                        mAdapter.notifyDataSetChanged();
                    }
                    getJSON();
                }
            }
        });
    }


    @Override
    protected void initView(View rootView) {

    }

    @Override
    protected void initData() {


    }

    @Override
    protected void initClick() {


    }
    private void upView(){
        refresh = 1;
        page = 1;
        mArrayList.clear();
        if (mAdapter != null) {
            mAdapter.notifyDataSetChanged();
        }
        isWU = false;
        getJSON();
    }
    public void getJSON() {
        activity.showLoad();
        RequestParams params = AllPublic.getParamsEvaluate(activity, "/evaluateList", false);

        params.addParameter("productId",goods_id);
        params.addParameter("type",0);
        params.addParameter("currentPage",page);
        params.addParameter("pageSize", Config.ROWS);
        Log.d("评价", "getJSON: "+params);
        //请求
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override  //成功
            public void onSuccess(String result) {
                Log.d("评价：", result);
                try {
                    JSONObject jsonObject= new JSONObject(result);
                    String reason = jsonObject.getString("code");
                    if (reason.equals("0")) {
                        JSONObject data = jsonObject.getJSONObject("data");
                        JSONArray records = data.getJSONArray("evaluate");
                        Evaluate commodity=null;
                        if (records.length()< Config.ROWS){
                            isWU=true;
                        }
                        for (int i=0;i<records.length();i++){
                            commodity=new Evaluate();
                            JSONObject object = records.getJSONObject(i);
                            double evaluationScore = object.has("evaluationScore") ? object.getDouble("evaluationScore") : 0;//评分
                            String evaluationImage = object.has("evaluationImage") ? object.getString("evaluationImage") : "";//评价图片
                            String merchantsHeadPortrait = object.has("merchantsHeadPortrait") ? object.getString("merchantsHeadPortrait") : "";//用户头像
                            String cmIndate = object.has("cmIndate") ? object.getString("cmIndate") : "";//评价时间
                            String evaluationContent = object.has("evaluationContent") ? object.getString("evaluationContent") : "";//评价内容
                            String merchantName = object.has("merchantName") ? object.getString("merchantName") : "";//评价用户名

                            commodity.setEvaluationScore(evaluationScore);
                            commodity.setEvaluationImage(evaluationImage);
                            commodity.setMerchantsHeadPortrait(merchantsHeadPortrait);
                            commodity.setCmIndate(cmIndate);
                            commodity.setEvaluationContent(evaluationContent);
                            commodity.setMerchantName(merchantName);
                            mArrayList.add(commodity);
                        }
                        handler.sendEmptyMessage(1);
                    }else {
                        toastWk(jsonObject.getString(getResources().getString(R.string.errMsg)));
                    }
                } catch (Exception e) {
                    e.printStackTrace();

                }
                activity.  dismissLoad();
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

                ex.printStackTrace();
                activity. dismissLoad();
            }
            @Override
            public void onCancelled(CancelledException cex) {

                activity.  dismissLoad();
            }
            @Override
            public void onFinished() {

                activity.   dismissLoad();
            }
        });
    }
    private void loadData() {
        if (mAdapter==null){
            mAdapter=new Q2_List_Adapter(mActivity,mActivity, mArrayList);
            mLoadListView.setAdapter(mAdapter);
        }else {
            mAdapter.notifyDataSetChanged();
        }
        if (refresh == 1) {
            mPullToRefreshLayout.finishRefresh();//下拉刷新
        } else if (refresh == 2) {
            mPullToRefreshLayout.finishLoadMore();//上啦加载
        }
        activity. dismissLoad();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mArrayList!=null){
            mArrayList.clear();
        }
        if (mAdapter!=null){
            mAdapter=null;
        }
    }

    @Override
    protected int setLayoutResouceId() {
        return 0;
    }
}
